<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model;
use think\Config;
use app\admin\model\Dept as DeptModel;

class Organize extends Base {

    protected $org_type = array(
        1 => '总店',
        2 => '加盟商',
    );


    public function index() {
        $org_type = input('org_type', 1);
        $company_id = input('company_id', 0);
        $isvalid = input('isvalid');
        $where = array();
        $where['org_type'] = $org_type;
        if ($company_id) {
            $where['id'] = $company_id;
        }
        if (isset($isvalid) && $isvalid!='') {
            $where['isvalid'] = intval($isvalid);
          
        }
        $data = Db::name('organize')->field('*')->where($where)->order('id desc')->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);
        $show = $data->render();
        $show = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)", "<a href='javascript:ajax_page($1);'>$2</a>", $show);
        $this->assign('org_type_arr', $this->org_type);
        $this->assign('company_id', $company_id);
        $this->assign('org_type', $org_type);
        $this->assign('data', $data);
        $this->assign('page', $show);
        $this->assign('isvalid', $isvalid);
        
        if (request()->isAjax()) {
            return $this->fetch('ajax_org_list');
        } else {
            return $this->fetch();
        }
    }

    /**
     * 异步根据输入名获取公司信息
     */
    public function ajaxGetCompanyInfoByName() {
        $org_type = input('org_type', 1);
        $name = strip_tags(input('term')); //搜索字段
        $cond_where = array();
        if (!empty($name)) {
            $cond_where['name'] = array('LIKE', '%' . $name . '%');
        }
        if ($org_type) {
            $cond_where['org_type'] = intval($org_type);
        }
        $org = Db::name('organize')
                ->where($cond_where)
                ->field('id,name')
                ->select();
        if (empty($org)) {
            $org[0]['id'] = 0;
            $org[0]['name'] = '无符合条件的用户信息';
        }
        return(json_encode($org));
    }

    /**
     * 公司部门列表
     */
    public function dept() {
        $org_id = input("org_id");
        $where['org_id'] = $org_id;
        $data = Db::name('dept')->where($where)->order('pid ASC,id ASC')->select();
//        var_dump($data);exit;
        $menu = menu_left($data, 'id', 'pid');
        $this->assign('menu', $menu);
        $this->assign('org_id', $org_id);
        if (request()->isAjax()) {
            return $this->fetch('ajax_dept');
        } else {
            return $this->fetch();
        }
    }

    /**
     * 公司部门编辑
     */
    public function deptEdit() {
        $org_id = input("org_id");
        $dept_id = input("dept_id");
        $dept = Db::name('dept')->where(array('id' => $dept_id))->find();
        $where['org_id'] = $org_id;
        $data = Db::name('dept')->where($where)->order('pid ASC,id ASC')->select();
        $menu = menu_left($data, 'id', 'pid');
        $this->assign('menu', $menu);
        $this->assign('org_id', $org_id);
        $this->assign('dept', $dept);
        return $this->fetch();
    }

    /**
     * 公司部门编辑
     */
    public function deptEditSubmit() {
        $id = input("dept_id");
        $org_id = input("org_id");
        $name = input('name');
        $pid = input('pid');
        $isvalid = input('isvalid');
        $data = array(
            'id' => $id,
            'name' => $name,
            'org_id' => $org_id,
            'pid' => $pid,
            'isvalid' => $isvalid,
            'update_time'=>time()
        );
        //数据校验
        $result=$this->validate($data,'OrganizeDept');
        if(true!==$result){
            //如果通不过,显示错误信息,并阻止页面提交
            $this->error($result);
        }
        $info = Db::table('dept')->update($data);
        if ($info !== false) {
            $this->success('编辑成功！', url('admin/Organize/dept',array('org_id' => $org_id)));
        } else {
            $this->error('编辑失败！');
        }
    }


    /**
     * 公司部门添加
     */
    public function deptAdd() {
        $org_id = input("org_id");
        $where['org_id'] = $org_id;
        $data = Db::name('dept')->where($where)->order('pid ASC,id ASC')->select();
        $menu = menu_left($data, 'id', 'pid');
        $this->assign('menu', $menu);
        $this->assign('org_id', $org_id);
        return $this->fetch();
    }

    /**
     * 公司部门添加提交
     */
    public function deptAddSubmit(){
        $org_id = input("org_id");
        //$this->error(json_encode($_POST));
        //获取表单值
        $name = input('name');
        $pid = input('pid');
        $isvalid = input('isvalid');
        $data = array(
            'org_id' => $org_id,
            'name' => $name,
            'pid' => $pid,
            'isvalid' => $isvalid,
            'create_time' => time()
        );
        //数据校验
        $result=$this->validate($data,'OrganizeDept');
        if(true!==$result){
            //如果通不过,显示错误信息,并阻止页面提交
            $this->error($result);
        }
        $info=Db::table('dept')->insert($data);
        if($info){
            $this->success('添加成功！', url('admin/Organize/dept',array('org_id' => $org_id)));
        }else{
            $this->error('添加失败！');
        }
    }

    /**
     *根据公司类别id，获得公司
     */
    public function getDataByType()
    {
        $code = '400';
        $msg = '获取数据失败';

        $org_list = array();
        $org_type = intval(input('org_type'));//公司类型id
        if(isset($org_type) && !empty($org_type)){
            $where_cond = array(
                'org_type' => $org_type,
                'isvalid' => 1
            );
            $org_list = db('organize')->where($where_cond)->select();
            if(is_array($org_list) && !empty($org_list)){
                $code = '200';
                $msg = '获取数据成功';
            }
        }

        return ['code'=>$code,'message'=>$msg,'data'=>$org_list];

    }

    /**
    *根据公司id获得部门数据
    */
    public function getDeptByOrgId()
    {
        $code = '400';
        $msg = '获取数据失败';
        
        $dept_list = [];
        $org_id = input('org_id/d', 0);//公司id
        if (isset($org_id) && !empty($org_id)) {
            $where_cond = [
                'org_id' => $org_id,
                'isvalid' => 1
            ];
            $dept_list = Db::name('dept')->where($where_cond)->field('id,pid,org_id,name')->select();

           if (is_array($dept_list) && !empty($dept_list)) {
                $code = '200';
                $msg = '获取数据成功';
            }
        }
        
        return json(['code' => $code, 'message' => $msg, 'data' => $dept_list]);
    }

    /**
     *根据公司id获得部门数据
     */
    public function getDeptTreeByOrgId()
    {
        $code = '400';
        $msg = '获取数据失败';

        $dept_list = [];
        $org_id = input('org_id/d', 0);//公司id
        if (isset($org_id) && !empty($org_id)) {
            $where_cond = [
                'org_id' => $org_id,
                'isvalid' => 1
            ];
            $dept_list = Db::name('dept')->where($where_cond)->field('id,pid,org_id,name')->select();
            $dept_tree_arr = returnTree($dept_list , array() , 0);

            if (is_array($dept_tree_arr) && !empty($dept_tree_arr)) {
                $code = '200';
                $msg = '获取数据成功';
            }
        }

        return json(['code' => $code, 'message' => $msg, 'data' => $dept_tree_arr]);
    }

    /**
     * 获取部门列表
     * @param
     */
    public function ajaxGetDeptListByOrgId()
    {
        $org_id = input('org_id/d');
        $dept_list = array();
        if(isset($org_id) && !empty($org_id)){
            $dept_model = new DeptModel();
            $dept_list = $dept_model->getDeptListByOrgIds($org_id);
        }
        return $dept_list;
    }
    
    /**
    * 新增公司
    */
    public function organizeAdd() {

        $type_val = $this->org_type;
        $this->assign('org_type', $type_val);

        return $this->fetch();
    }

    /**
    * 新增公司表单处理
    */
    public function organizeHandle() {
        //获取表单值
        $data = array(
            'name' => input('name'),
            'org_type' => 2,
            'juristic_person' => input('juristic_person'),
            'registered_capital' => input('registered_capital'),
            'currency' => input('currency'),
            'unified_coding' => input('unified_coding'),
            'create_time' => time()
        );
        //数据校验
        $result=$this->validate($data,'Organize');

        if(true!==$result){
            //如果通不过,显示错误信息,并阻止页面提交
            $this->error($result);
        }
        $data['registered_capital'] = $data['registered_capital'].'万'.$data['currency'];
        unset($data['currency']);
        $id = Db::name('organize')->insert($data);

        if (isset($id)) {
            $this->success('添加成功！', url('admin/Organize/index',array("org_type"=>$data['org_type'])));
        } else {
            $this->error('添加失败！');
        }
    }

    /**
     * 修改公司表单处理
     */
    public function organizeEdit() {
        $id = input('id');
        $data = Db::name('organize')->where('id', $id)->find();
        $currency = strstr($data['registered_capital'],'万');
        $data['registered_capital'] = str_replace($currency,'',$data['registered_capital']);
        $data['currency'] = substr($currency,3);
        $this->assign('data', $data);
        $this->assign('org_type', $this->org_type);

        return $this->fetch();
    }

    /**
     * 修改公司表单提交处理
     */
    public function organizeEditSubmit() {

            $id = input('id');
            $org_type = input('org_type');
            //获取表单值
            $data_sql['id'] = $id;
            $data_sql['name'] = input('name');
            $data_sql['juristic_person'] = input('juristic_person');
            $data_sql['registered_capital'] = input('registered_capital');
            $data_sql['currency'] = input('currency');
            $data_sql['unified_coding'] = input('unified_coding');
            $data_sql['update_time'] = time();
            $data_sql['isvalid'] = input('isvalid', '', 'intval');
            //数据校验
            $result=$this->validate($data_sql,'Organize');

            if(true!==$result){
                //如果通不过,显示错误信息,并阻止页面提交
                $this->error($result);
            }
            $data_sql['registered_capital'] = $data_sql['registered_capital'].'万'.$data_sql['currency'];
            unset($data_sql['currency']);
            $data_id = Db::name('organize')->update($data_sql);

            if (isset($data_id)) {
                $this->success('编辑成功！', url('admin/Organize/index', array('org_type' => $org_type)));
            } else {
                $this->error('编辑失败！');
            }
    }

    /**
     * 公司账号设置
     */
    public function setAcount() {
        $org_id = input('id');
        $userInfo = Db::name('user')->where(array('org_id' => $org_id, 'user_type' => 2))->find();
        if (isset($userInfo)) {
            return (json($userInfo));
        } else {
            return 0;
        }
    }

    /**
     * 公司账号设置提交
     */
    public function setAccountSubmit() {
        $id = input('br_id', 0, 'intval');
        $user_name = input('user_name');
        $org_id = input('org_id');
        $password = input('password');
        if ($id == 0) {
            $info = Db::name('user')->where(array('user_name' => $user_name))->find();
            if ($info) {
                $this->error('此账户名已存在，请修改后再试！');
            } else {
                $org_info = Db::name('organize')->find($org_id);
                //$this->error(json_encode($org_info['telephone'])); 
                $data = array(
                    'org_id' => $org_id,
                    'name' => '总账号',
                    'user_name' => $user_name,
                    'password' => md5(trim($password)),
                    'user_type' => 2,
                    'isvalid' => 1,
                    'create_time' => time()
                );
            }
            $insert_id = Db::name('user')->insertGetId($data);
            if (isset($insert_id)) {
                $group = Db::name('auth_group')->where('title','开发商组')->find();
                $arr['uid'] = $insert_id;
                $arr['group_id'] = $group['id'];
                $info = Db::name('auth_group_access')->insert($arr);
                $this->success('添加成功！');
            } else {
                $this->error('添加失败！');
            }
        } else {
            $where['user_name'] = $user_name;
            $where['id'] = array('neq', $id);
            $info = Db::name('user')->where($where)->find();
            if (isset($info)) {
                $this->error('此账户名已存在，请修改后再试！');
            } else {
                $checkpassword = Db::name('user')->where(array('id' => $id))->find();
                //$this->error(json_encode($checkpassword['password']));
                if ($checkpassword['password'] == $password) {
                    $passwordedit = $password;
                } else {
                    $passwordedit = md5(trim($password));
                }
                $data = array(
                    'id' => $id,
                    'user_name' => $user_name,
                    'password' => $passwordedit,
                    'update_time' => time()
                );
                $update_id = Db::name('user')->update($data);
                if (isset($update_id)) {
                    $this->success('编辑成功！');
                } else {
                    $this->error('编辑失败！');
                }
            }
        }
    }

}